xquery version "0.9-ml"

(:~
 : This library module contains functions that can be used accross all
 : services and XQuery modules.
 :
 :)

module "http://marklogic.com/ps/common"

(: we don't want to have to prefix the fn:* functions :)
default function namespace = "http://www.w3.org/2003/05/xpath-functions"

declare namespace cm = "http://marklogic.com/ps/common"

(:~ The paramater that request XML for our REST services will be passed in on. :)
define variable $REQUEST-PARAMETER as xs:string {"request"}

define variable $MALFORMED-CODE as xs:string {"malformed"}

(:~
 : Get the request element for the current service call.  This assumes that it
 : is being passed in under the parameter $REQUEST-PARAMETER
 :
 : $default - default elements that should be put inside of a request element
 :)
define function cm:get-request-element($default as element()*) as element(request)
{
  let $requestString := xdmp:get-request-field($REQUEST-PARAMETER)
  let $retval := 
    if ($requestString) then
      let $requestElement := xdmp:unquote($requestString)/element()
      return 
        typeswitch ($requestElement) 

	  case element(request)
	  return 
	    (
	      if ($requestElement/@debug = "on") then
		(
		  xdmp:log("common.xqy, get-request-element: turning query-trace on", "info"),
		  xdmp:query-trace(true())
                )
	      else
		(),
		 
              $requestElement
            )
	
          default return <request>{$requestElement}</request>
      
    else (: if ($requestString) :)
      if ($default) then
        <request>
          { $default }
        </request>
      else
        error($MALFORMED-CODE, concat("common.xqy, No ", $REQUEST-PARAMETER, " parameter present and no default available."))

  let $action-check := 
    if ($retval/element()) then () else
        error($MALFORMED-CODE, concat("Unable to find request type element under request.  Request is malfromed: ",
      xdmp:quote($retval)))
  let $debug := xdmp:log(concat("common.xqy, get-request-element: deserialized request - ", xdmp:quote($retval)), "info")

  return $retval
}
